import requests
import os
from urllib.parse import urlparse
import time

def download_image(url, save_dir=None):
    """
    下载网络图片并保存到指定目录
    
    Args:
        url: 图片URL
        save_dir: 保存目录（默认为脚本所在目录的 images 文件夹）
    """
    try:
        # 如果未指定保存目录，使用默认目录
        if save_dir is None:
            current_dir = os.path.dirname(os.path.abspath(__file__))
            save_dir = os.path.join(current_dir, 'images')
        
        # 确保保存目录存在
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        
        # 从URL中获取文件名
        filename = os.path.basename(urlparse(url).path)
        if not filename:
            filename = 'downloaded_image.jpg'
        
        # 构建保存路径
        save_path = os.path.join(save_dir, filename)
        
        # 发送请求下载图片
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 检查请求是否成功
        
        # 保存图片
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
        
        print(f"图片已成功下载到: {save_path}")
        return save_path
        
    except Exception as e:
        print(f"下载图片时发生错误: {str(e)}")
        return None

def download_project_images(project_name, algorithm_code, save_dir):
    """
    获取项目图片列表并下载所有图片
    
    Args:
        project_name: 项目名称
        algorithm_code: 算法代码
        save_dir: 保存目录
    """
    try:
        # API 配置
        url = "http://localhost:8080/ai-push-results/list"
        headers = {
            "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1dWlkIjoicGVybWFuZW50XzBiYzI1YWM4OWIzZjQzZjVhMmY5YzNjMGVmYTMzZThhIiwidXNlcklkIjoxMDgsImlhdCI6MTc0NDM1OTk3MX0.grZuEaACpuWcyhWTBw2LOd4EyGE9rMJ6-nNEyWxMKN0",
            "Content-Type": "application/json"
        }
        
        # 请求参数
        data = {
            "projectName": project_name,
            "pageNum": 1,
            "pageSize": 999,
            "isHistory": 1,
            "algorithmCode": algorithm_code
        }
        
        # 发送请求
        response = requests.post(url, json=data, headers=headers)
        response.raise_for_status()
        result = response.json()
        
        if result.get('code') != 200:
            print(f"获取列表失败: {result.get('msg')}")
            return
        
        # 获取图片列表
        image_list = result.get('data', {}).get('list', [])
        total = len(image_list)
        print(f"找到 {total} 张图片")
        
        # 下载每张图片
        for index, item in enumerate(image_list, 1):
            image_url = item.get('imageOriginalStr')
            if not image_url:
                print(f"跳过第 {index} 项：未找到图片URL")
                continue
                
            print(f"\n正在下载第 {index}/{total} 张图片:")
            print(f"URL: {image_url}")
            
            # 下载图片
            downloaded_path = download_image(image_url, save_dir)
            
            # 添加短暂延时避免请求过快
            time.sleep(0.5)
            
        print("\n所有图片下载完成！")
        
    except Exception as e:
        print(f"获取或下载图片时发生错误: {str(e)}")

if __name__ == '__main__':
    # 示例URL
    image_url = "https://xunjikejiai.site/miniofile/illegal-construction/2025/04/11/images/p6zvctqf8hwsyfjbpb5kaoneo2t82ksa.jpg"
    
    # 指定保存目录（可选）
    save_directory = r"d:\xunJi\python\my\tools\images\download"
    
    # 下载图片
    # downloaded_path = download_image(image_url, save_directory)

    # 执行批量下载
    download_project_images('daxin', 'zhatu', save_directory)